<template>
  <div class="picker">
    <lzc-file-picker ref="dirShared" base-url="/_lzc/files/home"
      type="directory" title="选择保存位置" confirm-button-title="保存" @visible="showLzcDirPicker= false"
      @submit="submitLzcDirPicker">
    </lzc-file-picker>
    <div @click="showLzcDirPicker = true"><slot></slot></div>
  </div>
</template>

<script lang="ts" setup>
import { watch, nextTick, ref } from 'vue'
const props = defineProps({
  modelValue: {
    type: String,
    default: '/',
  },
})
const emit = defineEmits(['update:modelValue'])
// const emits = defineEmits<{
//   (event: 'update:modelValue'): void
// }>()

const dirShared = ref()
const showLzcDirPicker = ref(false)
const submitLzcDirPicker = (e: CustomEvent) => {
  const Dir = dataTransfer<FileStat>(e)
  const v = Dir?.filename || '/'
  emit('update:modelValue', v)
  showLzcDirPicker.value = false
}
async function invoke(instance: any, method: string, ...args: string[]) {
  await nextTick()
  const exposed = instance.value._instance.exposed
  !!exposed[method] && exposed[method](...args)
}
watch(showLzcDirPicker, (newVal) => {
  if (newVal) {
    invoke(dirShared, 'init')
    invoke(dirShared, 'open')
  }
  else {
    invoke(dirShared, 'close')
  }
})
function dataTransfer<T>(raw: any) {
  if (!raw) return
  const output = raw.detail[0]
  return output as T
}
interface FileStat {
  filename: string;
  basename: string;
  lastmod: string;
  size: number;
  type: 'file' | 'directory';
  etag: string | null;
  mime?: string;
  props?: DAVResultResponseProps;
}
interface DAVResultResponseProps {
  displayname: string;
  resourcetype: {
    collection?: boolean;
  };
  getlastmodified?: string;
  getetag?: string;
  getcontentlength?: string;
  getcontenttype?: string;
  'quota-available-bytes'?: any;
  'quota-used-bytes'?: string;
}
</script>
<style lang="scss" scoped>
.picker {
  display: inline;
  margin: 0 10px;
  div {
    display: inline;
    cursor: pointer;
  }
}
</style>